<template>
  <div class="app-container">
    <div v-show="tab_view==1" class="customContainer">
      <el-form :model="formInline" :inline="true" size="small">
        <el-form-item>
          <el-select v-model="formInline.sell_type" style="width:100px" @change="sellChange">
            <el-option v-for="item in coupon_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span>类型：</span>
          <el-select v-if="formInline.sell_type==1" v-model="formInline.type" style="width:100px">
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-if="formInline.sell_type==2" v-model="formInline.type" style="width:100px">
            <el-option v-for="item in commodity_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span>渠道：</span>
          <el-select v-model="formInline.channel" style="width:100px">
            <el-option v-for="item in channel_list" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disable">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span>状态：</span>
          <el-select v-model="status" multiple collapse-tags style="width:150px">
            <el-option v-for="item in status_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span>上下架：</span>
          <el-select v-model="formInline.is_sell" style="width:100px">
            <el-option v-for="item in put_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.name" placeholder="请输入名称" style="width:150px;" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="setSale">新建销售</el-button>
      </el-form>
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="mini">
        <el-table-column align="center" label='名称' prop="name" width="250">
        </el-table-column>
        <el-table-column align="center" label='类型'>
          <template slot-scope="scope">
            <span v-if="!isPro&&scope.row.type==1">代金券</span>
            <span v-if="isPro&&scope.row.type==2">办卡</span>
            <span v-if="isPro&&scope.row.type==3">充值</span>
            <span v-if="isPro&&scope.row.type==4">续期</span>
            <span v-if="isPro&&scope.row.type==6">企划</span>
            <span v-if="isPro&&scope.row.type==7">实物</span>
            <span v-if="isPro&&scope.row.type==5">门票</span>
            <span v-if="isPro&&scope.row.type==8">凭证兑换</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="说明" prop="descrip" width="300">
        </el-table-column>
        <el-table-column align="center" label="渠道">
          <template slot-scope="scope">
            <span v-if="scope.row.channel==1">小程序</span>
            <span v-if="scope.row.channel==2">收银台</span>
            <span v-if="scope.row.channel==3">自助终端</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="领取/售卖时间" width="260">
          <template slot-scope="scope">
            <span>{{scope.row.sell_time_begin}}~{{scope.row.sell_time_end}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status==1">未开始</span>
            <span v-if="scope.row.status==2">进行中</span>
            <span v-if="scope.row.status==3">已结束</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间" prop="update_time" width="150">
        </el-table-column>

        <el-table-column align="center" label="分销状态">
          <template slot-scope="scope" v-if="scope.row.channel==1">
            <span v-if="scope.row.distribution_id <= 0">无分销</span>
            <span v-if="scope.row.distribution_status == 0 && scope.row.distribution_id > 0">已启用</span>
            <span v-if="scope.row.distribution_status == 1 && scope.row.distribution_id > 0">已停用</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="上下架">
          <template slot-scope="scope">
            <span style="margin-left:10px" v-if="scope.row.is_sell==3">自动上架</span>
            <el-switch v-else :disabled="scope.row.status==3" v-model="scope.row.is_sell" @change="changeClick(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label='操作' width="220">
          <template slot-scope="scope">
            <el-button type="primary" :disabled="scope.row.channel!=1" size="mini" plain @click="distribution(scope.row)">分销</el-button>
            <el-button type="primary" size="mini" plain @click="seeInfo(scope.row.id,formInline.sell_type,scope.row.type)">详情</el-button>
            <el-button type="danger" v-if="scope.row.status!=3" size="mini" plain @click="endInfo(scope.row.is_sell,scope.row.id,scope.$index)">结束</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="tab_view==1" class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>

    <!-- 弹框 -->
    <el-dialog  title="分销配置" :visible.sync="addTypeDialog" width="1200px">
      <div class="main">
        <el-form>
          <div class="op_title" style="margin-top: 0">分销次数</div>
          <el-form-item label="最多分享成功" style="padding-left: 30px;box-sizing: border-box">
            <template>
              <el-input type="number" :disabled="isDisabled" v-model="distributionFrom.number" placeholder="1~999" style="width: 150px;margin: 0 5px 0 10px"></el-input>
              <span>次</span>
              <span style="margin-left: 20px;font-size: 14px;color: #ccc">分享成功：分享给好友且好友购买成功后同时获得福利。</span>
            </template>
          </el-form-item>
          <div class="op_title">分销福利  <span style="color: #ccc;font-size: 14px">最多可选择1份商品/券</span></div>
          <el-table stripe highlight-current-row :data="distributionFrom.distributionList" border size="mini" class="table">
            <el-table-column align="center" label='选择' width="50">
              <template slot-scope="scope">
                <el-radio v-model="distributionRadio" :label="scope.$index+1" :disabled="isDisabled"><em></em></el-radio>
              </template>
            </el-table-column>
            <el-table-column align="center" label="获得者" prop="typeName"></el-table-column>
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
            <el-table-column align="center" label='操作'>
              <template slot-scope="scope">
                <el-button :disabled="isDisabled" type="danger" size="mini" @click="delRelevance(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="op_title" >选择商品/券</div>
          <el-form :inline="true" :model="relevanceFrom" ref="relevanceForm" size="small" :disabled="isDisabled">
            <el-form-item>
              <el-select
                      v-model="relevanceFrom.sell_type"
                      style="width:100px"
                      @change="relevanceFromType"
                      filterable
              >
                <el-option
                        v-for="item in relevance_list"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <span style="color: #888;">类型：</span>
              <el-select
                      v-model="relevanceFrom.type"
                      style="width:100px"
                      filterable
              >
                <el-option
                        v-for="item in relevance_type"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="name">
              <el-input
                      v-model="relevanceFrom.name"
                      placeholder="请输入商品名称"
                      @keyup.enter.native="commodity"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <dj-button size="small" @search="commodity">
                <template #default>搜索</template>
              </dj-button>
            </el-form-item>
          </el-form>
          <el-table highlight-current-row :data="relevancelist" border size="mini" height="240px"  v-loading.body="listLoading">
            <el-table-column align="center" label='序号' width="50">
              <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
            <el-table-column align="center" label='操作'>
              <template slot-scope="scope">
                <el-button  type="primary" size="mini" @click="addRelevance(scope.row)" :disabled="isDisabled">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
                  background
                  @current-change="relevanceCurrentChange"
                  :current-page.sync="relevancePage"
                  :page-size="20"
                  layout="prev, pager, next, jumper"
                  :page-count="relevanceTotal"
                  style="margin-top: 5px"
          ></el-pagination>
          <div class="op_title" >分销状态</div>
          <div style="margin-left: 20px">
            <el-radio-group v-model="distributionFrom.startUsing ">
              <el-radio label="0">启用</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </div>
        </el-form>
        <div style="text-align:right;margin-bottom:20px">
          <el-button @click="saveClick" v-if="!isDisabled" type="primary" size="small">保存</el-button>
          <el-button @click="saveStatus" type="primary" v-else size="small">修改</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新建销售/销售详情 -->
    <div v-show="tab_view==2" class="customContainer">
      <el-button class="pull-left" type="primary" size="small" @click="goBack">返 回</el-button>
      <div class="tab_title">{{top_title}}</div>
      <div v-show="isNew">
        <dj-tab :data='step_list' :isNew='isNew' :tab_step='tab_step' @goStep='nowTop'></dj-tab>
      </div>
      <div class="info">
        <div v-show="tab_step==1">
          <div class="content">
            <el-form :model="search" :inline="true" size="mini">
              <el-form-item>
                <el-select :disabled="disable" v-model="search.sell_type" style="width:100px" @change="searchChange">
                  <el-option v-for="item in coupon_list" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <span>类型：</span>
                <el-select v-if="search.sell_type==1" v-model="search.type" style="width:100px" :disabled="disable">
                  <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <el-select v-else v-model="search.type" style="width:100px" :disabled="disable">
                  <el-option v-for="item in commodity_list" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input :disabled="disable" v-model="search.name" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" :disabled="disable" @click="getList">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table stripe highlight-current-row :data="tableData" border size="mini" height="400" class="table" style="width:888px">
              <el-table-column align="center" width="50">
                <template slot-scope="scope">
                  <el-radio v-model="saveFrom.coupons_id" :label="scope.row.id" :disabled="disable" @change="couIdChange"><em></em></el-radio>
                </template>
              </el-table-column>
              <el-table-column align="center" label='名称' prop="name">
              </el-table-column>
              <el-table-column align="center" label='类型'>
                <template slot-scope="scope">
                  <span v-if="!editPro&&scope.row.type==1">代金券</span>
                  <span v-if="editPro&&scope.row.type==2">办卡</span>
                  <span v-if="editPro&&scope.row.type==3">充值</span>
                  <span v-if="editPro&&scope.row.type==4">续期</span>
                  <span v-if="editPro&&scope.row.type==5">门票</span>
                  <span v-if="editPro&&scope.row.type==6">企划</span>
                  <span v-if="editPro&&scope.row.type==7">实物</span>
                  <span v-if="editPro&&scope.row.type==8">凭证兑换</span>
                </template>
              </el-table-column>
            </el-table>
            <div style="overflow: hidden;">
              <el-pagination :disabled="disable" style="margin-top:10px;" class="pull-left" background @current-change="handleCurrent" :current-page.sync="page"
                :page-size="20" layout="prev, pager, next, jumper" :total="totalNumber">
              </el-pagination>
            </div>
            <div class="title">销售渠道</div>
            <div style="padding:10px 0;">
              <el-radio-group v-if="obj_type==8" v-model="saveFrom.channel" :disabled="disable">
                <el-radio :label="2">收银台</el-radio>
                <el-radio :label="4" disabled>PDA</el-radio>
              </el-radio-group>
              <el-radio-group v-else v-model="saveFrom.channel" :disabled="disable">
                <el-radio :label="1">小程序</el-radio>
                <el-radio :label="2" :disabled="isCashierDesk">收银台</el-radio>
                <el-radio :label="3" disabled>自助终端</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
        <div v-show="tab_step==2">
          <div class="content">
            <!-- 可售库存 -->
            <div class="title">可售库存</div>
            <el-checkbox v-model="noNum" :disabled="disable||num!=''||saveFrom.store_sell_num!=''||show_num!=''">无限制</el-checkbox>
            <span class="span">总库存：</span>
            <el-input style="width:200px;margin-bottom:10px;" :disabled="disable||noNum!=''||saveFrom.store_sell_num!=''||obj_type==8"
              @change="inputIn($event,0,999999,1)" v-model="num" size="small" type="number" v-vue-onkeypress>
            </el-input>
            <i>{{text}}</i>
            <span class="span">单门店库存：</span>
            <el-input style="width:200px" :disabled="disable||noNum!=''||num!=''||obj_type==8" @change="inputIn($event,0,999999,1)"
              v-model="saveFrom.store_sell_num" size="small" type="number" v-vue-onkeypress>
            </el-input>
            <i>{{text}}</i>
            </br>
            <el-checkbox :disabled="disable||noNum!=''||obj_type==8" v-model="show_num" style="width:200px;">显示剩余库存</el-checkbox>
            <span class="span">勾选并上架后，用户可看到剩余库存数</span>
            <!-- 售卖时间 -->
            <div class="title">售卖时间</div>
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm" :picker-options="pickerOptions" type="datetimerange" align="right"
              unlink-panels range-separator="-" :clearable="false" :disabled="disable" size="small" v-model="time" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <span class="span">用户在可售卖时间段内，且该券处于上架状态，则可以购买</span>
            <!-- 限购数量 -->
            <div class="title">限购数量</div>
            <el-checkbox :disabled="disable||obj_type==8" v-model="checked1" @change="checkeChange" style="width:170px;">单个用户</el-checkbox>
            <el-select :disabled="disable||!checked1" v-model="saveFrom.limit_time" style="width:100px;margin-bottom:10px;" size="small">
              <el-option v-for="item in day_list" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <span class="span"> 购买上限：</span>
            <el-input v-model="saveFrom.limit" @change="inputIn($event,1,9999,2)" :disabled="disable||!saveFrom.limit_time||!checked1||obj_type==8"
              style="width:200px;" size="small" type="number" v-vue-onkeypress></el-input>
            <i>{{text}}</i>
            </br>
            <el-checkbox :disabled="disable||obj_type==8" @change="checkeChange" v-model="checked2" style="width:200px;">单个用户总购买上限</el-checkbox>
            <el-input v-model="saveFrom.all_limit" @change="inputIn($event,1,999,3)" :disabled="disable||!checked2||obj_type==8" style="width:200px;"
              size="small" type="number" v-vue-onkeypress></el-input>
            <i>{{text}}</i>
            <span class="span">单个用户在可售卖时间段内最多购买张数</span>
            <!-- 促销方式 -->
            <div class="title">促销方式</div>
            <el-checkbox :disabled="disable||obj_type==8||noNum!=''" v-model="is_crazy" style="width:200px;">抢购</el-checkbox>
            <span class="span">售卖结束时间剩余72小时开始倒计时，精确到秒。</span>
            <!-- 上下架 -->
            <div class="title">上下架</div>
            <el-radio-group :disabled="disable" v-model="saveFrom.status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
              <el-radio :label="2">自动上架（售卖开始时自动上架）</el-radio>
              <span class="span">上架后用户能看到该券，在可售卖时间段内可以购买。下架后不可购买，也不可见</span>
            </el-radio-group>
          </div>
        </div>
        <div style="margin-top:10px" v-if="!disable">
          <el-button type="primary" size="small" class="pull-right" v-show="tab_step==2" @click="preservation">保存</el-button>
          <el-button type="primary" size="small" class="pull-right mr_10" @click="goNext" v-show="tab_step==1">下一步</el-button>
          <el-button type="primary" size="small" class="pull-right" style="margin-right:10px" @click="goPrev" v-show="tab_step==2">上一步</el-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { djTab } from '@/components/tab';
import { pickerDateDot,getGoodsType } from '@/utils';
import {
  integer1to999
} from "@/utils/validate";
import {
  getList,
  getPage,
  verify_selling,
  set_sell_status,
  get_coupons_list,
  get_coupons_list_page,
  sell_modify,
  sell_info,
  goods_page,
  goods_list,
  distribution_svea,
  distribution_info,
  distribution_status
} from '@/api/operation/sales_management';
export default {
  components: {
    'dj-tab': djTab
  },
  data() {
    return {
      obj_type: '',
      text: '张',
      status: [1, 2],
      editPro: false,
      isPro: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },

      //以下为分销弹框
      isDisabled:false, //是否可更改
      addTypeDialog: false, // 弹窗是否显示
      distributionDate:"",//当前要被分销的数据
      distributionRadio:"",
      dialoglist:[{typeName:"分享者"},{typeName:"被分享者"}],
      distributionFrom:{
        number:"",
        startUsing:"",
        distributionList:[], //弹窗分销数据
      },
      relevancelist:[],
      relevancePage: 1,
      relevanceTotal: 0,
      relevance_list:[{ id: "", name: "全部" },{ id: "1", name: "优惠券" },{ id: "2", name: "商品" },],
      relevance_type:[],
      type_list1: [
        { id: "0", name: "全部" },
        { id: "2", name: "办卡" },
        { id: "3", name: "充值" },
        { id: "4", name: "续期" },
        { id: "5", name: "门票" },
        { id: "6", name: "企划" },
        { id: "7", name: "实物" },
      ],
      con_type_list: [
        { id: "1", name: "代金券" },
      ],
      relevanceFrom:{
        //商品搜索
        type:"",
        name: "",
        sell_type:""
      },
        //以上为分销弹框
      isCashierDesk: false, // 是否使用收银台
      checked1: false,
      checked2: false,
      num: '',
      noNum: '',
      time: '',
      isNew: 1,
      show_num: false,
      is_crazy: false,
      saveFrom: {
        is_crazy: 0,
        store_sell_num: '',
        show_num: 0,
        channel: 1,
        coupons_id: '',
        can_sell_num: '',
        sell_time_begin: '',
        sell_time_end: '',
        limit: '',
        limit_time: '',
        all_limit: '',
        status: 1,
        type: 1
      },
      tableData: [],
      listLoading: false,
      tab_step: 1,
      top_title: '新增销售',
      tab_view: '1',
      totalDataNumber: 0,
      totalNumber: 0,
      currentPage: 1,
      page: 1,
      disable: false,
      list: [],
      formInline: {
        sell_type: 1,
        type: 0,
        channel: '',
        status: [],
        is_sell: 0,
        name: '',
        coupons_id: ''
      },
      search: {
        sell_type: 1,
        type: 0,
        name: '',
        coupons_id: ''
      },
      step_list: [' 1.商品渠道', ' 2.销售设置'],
      day_list: [
        { id: 1, name: '单日' },
        { id: 2, name: '单周' },
        { id: 3, name: '单月' }
      ],
      coupon_list: [
        { id: 1, name: '优惠券' },
        { id: 2, name: '商品' }
      ],
      commodity_list: [
        { id: 0, name: '全部' },
        { id: 3, name: '充值' },
        { id: 2, name: '办卡' },
        { id: 4, name: '续期' },
        { id: 6, name: '企划' },
        { id: 7, name: '实物' },
        { id: 5, name: '门票' },
        { id: 8, name: '凭证兑换' }
      ],
      type_list: [
        { id: 0, name: '全部' },
        { id: 1, name: '代金券' },
        { id: 2, name: '满减券' }
      ],
      channel_list: [
        { id: 1, name: '小程序', disable: false },
        { id: 2, name: '收银台', disable: false },
        { id: 3, name: '自助终端', disable: true },
        { id: 4, name: 'PDA', disable: true }
      ],
      status_list: [
        { id: 1, name: '未开始' },
        { id: 2, name: '进行中' },
        { id: 3, name: '已结束' }
      ],
      put_list: [
        { id: 0, name: '全部' },
        { id: 2, name: '上架' },
        { id: 1, name: '下架' }
      ]
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.$route.params.routerflag) {
        //vm.saveFrom.coupons_id = vm.$route.params.id.toString();
        if (vm.$route.params.isNew === 1) {
          vm.search.sell_type = vm.$route.params.routerflag;
          vm.search.coupons_id = vm.$route.params.id;
          vm.tab_view = 2;
          vm.setSale();
        } else {
          vm.formInline.coupons_id = vm.$route.params.id;
          vm.formInline.sell_type = vm.$route.params.routerflag;
          vm.tab_view = 1;
          vm.fetchData();
        }
      } else {
        vm.fetchData();
      }
    });
  },
  methods: {
    couIdChange(val) {
      let obj = this.tableData.find(item => {
        return item.id == val;
      });
      if( this.search.sell_type !=2 || (this.search.sell_type ==2 && obj.type!=3 && obj.type!=4)){
        this.isCashierDesk = true;  
      }else{
        this.isCashierDesk = false;
      }
      this.saveFrom.channel = 1;
      this.obj_type = obj.type;
      if (obj.type == 8) {
        this.saveFrom.channel = 2;
      } else {
        this.saveFrom.channel = 1;
      }
    },

    //以下为分销弹框
    saveClick(){  //弹框保存
      if(!integer1to999(this.distributionFrom.number)){
        this.$message.error("请填写正确的分销次数");
        return
      }

      for(let i=0;i<this.distributionFrom.distributionList.length;i++){
        if(!('name' in this.distributionFrom.distributionList[i])){
          this.$message.error(`请选择《${this.dialoglist[i].typeName}》关联的商品/券`);
          return
        }
      }

      if(this.distributionFrom.startUsing == ""){
        this.$message.error("请选择分销状态");
        return
      }
      // console.log(this.distributionDate);  //当前弹框关联的那条数据
      // console.log(this.distributionFrom);
      let data={
        sell_id:this.distributionDate.id,
        times:this.distributionFrom.number,
        status:this.distributionFrom.startUsing,
        transpond:this.distributionFrom.distributionList[0].id,
        receive:this.distributionFrom.distributionList[1].id,
      }

      distribution_svea(data).then(res=>{
        if(res.code==1){
          this.$message.success(res.message);
          this.addTypeDialog=false;
          this.fetchData();
        }
      })
    },
    saveStatus(){
      if(this.distributionDate.distribution_status == this.distributionFrom.startUsing ){
        this.$message.error("状态没有进行更改！");
        return
      }
      distribution_status({
        id:this.distributionDate.distribution_id,
        status:this.distributionFrom.startUsing,
      }).then(res=>{
        if(res.code==1){
          this.$message.success(res.message);
          this.addTypeDialog=false;
          this.fetchData();
        }
      })
    },
    distribution(row){ //分销弹框显示
      if(this.relevancelist.length<=0){
        this.commodity();
      }
      if(row.distribution_id >0){
        distribution_info({id:row.distribution_id}).then(res=>{
          if(res.code==1){
            const listArray=this.getGoodsData([res.data.transpond_list,res.data.receive_list]);
            this.distributionFrom={
              number:res.data.times,
              startUsing:res.data.status,
              distributionList:[Object.assign({},this.dialoglist[0],listArray[0]),
                Object.assign({},this.dialoglist[1],listArray[1])]
            };
            this.distributionDate = row;
            this.addTypeDialog = true;
            if(row.status==1){
              this.isDisabled = false;
            }else{
              this.isDisabled = true;
            }
          }
        });
      }else{
        for(let i=0;i<this.dialoglist.length;i++){
          this.distributionFrom.distributionList[i]=this.dialoglist[i];
        }
        this.distributionRadio="";
        this.distributionFrom.number="";
        this.distributionFrom.startUsing="";
        this.isDisabled = false;
        this.distributionDate = row;
        this.addTypeDialog = true;
      }
    },
    addRelevance(row){  //添加商品
      if(this.distributionRadio){
        if(row.name == this.distributionFrom.distributionList[this.distributionRadio-1].name){
          this.$message.error("已添加成功，请勿重复添加");
        }else{
          const objLsit=Object.assign({},this.dialoglist[this.distributionRadio-1],row);
          this.$set(this.distributionFrom.distributionList,this.distributionRadio-1,objLsit);
        }
      }else{
        this.$message.error("请先选择分享福利获得者")
      }
    },
    delRelevance(index){ //移除商品
      const objLsit=this.dialoglist[index];
      this.$set(this.distributionFrom.distributionList,index,objLsit);
    },
    commodity(){
      this.listLoading = true;
      this.relevancelist = [];
      goods_page(this.relevanceFrom).then(response=>{
        this.relevanceTotal = response.data.page / 1;
        if (this.relevanceTotal == 0) {
          this.listLoading = false;
        } else {
          goods_list(this.relevanceFrom).then(res=>{
            this.relevancelist =  this.getGoodsData(res.data);
            this.listLoading = false;
          });
        }
      });
    },
    getGoodsData(data) {
      data.forEach((val) => {
        val.type_name = getGoodsType(val.type);
        val.time =
                val.chose_time_type == 1
                        ? val.effect_time.replace(/-/g, ".").replace(/,/g, "-")
                        : val.effect_time > 0
                        ? "购买后" + val.effect_time + "天内有效"
                        : "";
        val.time = val.time
                ? val.time
                : val.effect_time === "0"
                        ? "购买后当天有效"
                        : "购买后立即生效";
      });
      return data;
    },
    relevanceCurrentChange(val){
      this.listLoading = true;
      goods_list(this.relevanceFrom,val).then(res=>{
        this.relevancelist =  this.getGoodsData(res.data);
        this.listLoading = false;
      });
    },
    relevanceFromType(){
      if(this.relevanceFrom.sell_type=="2"){
        this.relevance_type=this.type_list1;
        this.relevanceFrom.type='0';
      }else if(this.relevanceFrom.sell_type=="1"){
        this.relevance_type=this.con_type_list;
        this.relevanceFrom.type='1';
      }else{
        this.relevanceFrom.type='';
      }
    },
    //以上为分销弹框
    sellChange() {
      if (this.formInline.sell_type == 1) {
        this.formInline.type = this.type_list[0].id;
      } else {
        this.formInline.type = this.commodity_list[0].id;
      }
      this.fetchData();
    },
    searchChange() {
      if (this.search.sell_type == 1) {
        this.search.type = this.type_list[0].id;
      } else {
        this.search.type = this.commodity_list[0].id;
      }
    },
    checkeChange() {
      if (this.checked1 == false) {
        this.saveFrom.limit_time = '';
        this.saveFrom.limit = '';
      }
      if (this.checked2 == false) {
        this.saveFrom.all_limit = '';
      }
    },
    //保存
    preservation() {
      if (this.checked1 == true && this.saveFrom.limit == '') {
        this.$message.error('请填写购买上限');
        return;
      }
      if (this.checked2 == true && this.saveFrom.all_limit == '') {
        this.$message.error('请填写总购买上限');
        return;
      }
      if (this.noNum == '' && this.num == '' && this.saveFrom.store_sell_num == '') {
        this.$message.error('未选择可售库存');
        return;
      }
      if (this.time == '') {
        this.$message.error('未选择售卖时间');
        return;
      }
      this.saveFrom.show_num = this.show_num ? 1 : 0;
      this.saveFrom.is_crazy = this.is_crazy ? 1 : 0;
      this.saveFrom.sell_time_begin = this.time[0];
      this.saveFrom.sell_time_end = this.time[1];
      this.saveFrom.can_sell_num = this.noNum == true ? 0 : this.num;
      this.saveFrom.type = this.search.sell_type;
      this.$confirm('确定创建销售?', {
        confirmButtonText: '确定',
        cancelButtonText: '返回修改'
      }).then(() => {
        sell_modify(this.saveFrom).then(res => {
          if (res.code == 1) {
            this.$message.success(res.message);
            this.tab_view = 1;
            this.saveFrom.coupons_id = '';
            this.formInline.coupons_id = '';
            this.formInline.sell_type = this.saveFrom.type;
            this.fetchData();
          }
        });
      });
    },
    //输入框数字上限及下线
    inputIn(value, min, max, num) {
      if (value < min) {
        switch (num) {
          case 1:
            this.num = min;
            break;
          case 2:
            this.saveFrom.limit = min;
            break;
          case 3:
            this.saveFrom.all_limit = min;
            break;
        }
      } else if (value > max) {
        switch (num) {
          case 1:
            this.num = max;
            break;
          case 2:
            this.saveFrom.limit = max;
            break;
          case 3:
            this.saveFrom.all_limit = max;
            break;
        }
      }
    },
    //详情
    seeInfo(Id, type, obj_type) {
      if (this.formInline.sell_type == 1) {
        this.text = '张';
        this.editPro = false;
      } else {
        this.text = '件';
        this.editPro = true;
      }
      this.obj_type = obj_type;
      this.isNew = 3;
      this.tableData = [];
      this.search.name = '';
      this.noNum = '';
      this.num = '';
      sell_info({ id: Id, sell_type: type }).then(res => {
        let data = res.data;
        let obj = {
          name: data.name,
          type: obj_type,
          id: Id
        };
        this.tableData.push(obj);
        if (data.can_sell_num / 1 > 0  || data.store_sell_num / 1 > 0) {
          this.num = data.can_sell_num/ 1 > 0 ?data.can_sell_num:"";
        } else {
          this.noNum = true;
        }
        this.time = [data.sell_time_begin, data.sell_time_end];
        this.saveFrom.status = data.status / 1;
        this.saveFrom.limit = data.limit / 1 > 0 ? data.limit : '';
        this.saveFrom.all_limit = data.all_limit / 1 > 0 ? data.all_limit : '';
        this.saveFrom.coupons_id = Id;
        this.saveFrom.limit_time = data.limit_time / 1 > 0 ? data.limit_time / 1 : '';
        this.saveFrom.store_sell_num = data.store_sell_num / 1 > 0 ? data.store_sell_num : '';
        this.show_num = data.show_num == 1 ? true : false;
        this.is_crazy = data.is_crazy == 1 ? true : false;
        this.saveFrom.channel = data.channel / 1;
        this.checked1 = data.limit_time / 1 >= 1 ? true : false;
        this.checked2 = data.all_limit / 1 >= 1 ? true : false;
      });
      this.top_title = '销售详情';
      this.tab_view = 2;
      this.disable = true;
    },
    getData(data) {
      data.forEach(val => {
        if (val.is_sell == 2) {
          val.is_sell = true;
        } else if (val.is_sell == 1) {
          val.is_sell = false;
        } else {
          val.is_sell = 3;
        }
      });
      this.list = data;
    },
    //下一步
    goNext() {
      if (this.saveFrom.coupons_id == '') {
        this.$message.error('未选择券和商品');
        return;
      }
      verify_selling({ coupons_id: this.saveFrom.coupons_id, channel: this.saveFrom.channel, type: this.search.sell_type })
        .then(res => {
          if (res.code == 1) {
            this.tab_step = 2;
          }
        })
        .catch(error => {});
    },
    //上一步
    goPrev() {
      this.tab_step = 1;
    },
    //新建销售
    setSale() {
      if (this.search.sell_type == 1) {
        this.text = '张';
      } else {
        this.text = '件';
      }
      this.getList();
      this.top_title = '新建销售';
      this.disable = false;
      this.tab_step = 1;
      this.tab_view = 2;
      this.time = '';
      this.saveFrom.channel = 1;
      this.saveFrom.can_sell_num = '';
      this.saveFrom.limit = '';
      this.saveFrom.limit_time = '';
      this.saveFrom.all_limit = '';
      this.saveFrom.status = 1;
      this.search.name = '';
      this.checked1 = false;
      this.checked2 = false;
      this.num = '';
      this.noNum = '';
      this.saveFrom.store_sell_num = '';
      this.show_num = false;
      this.is_crazy = false;
    },
    //详情步骤条点击事件
    nowTop(step) {
      if (this.disable) {
        this.tab_step = step;
      } else {
        return;
      }
    },
    //返回
    goBack() {
      if (!this.disable) {
        this.$confirm('确定返回？页面内容将失效！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tab_view = 1;
          this.saveFrom.coupons_id = '';
          this.search.coupons_id = '';
          this.obj_type = '';
        });
      } else {
        this.tab_view = 1;
        this.saveFrom.coupons_id = '';
        this.search.coupons_id = '';
        this.obj_type = '';
      }
    },
    //结束
    endInfo(is_sell, Id, index) {
      if (is_sell === true) {
        this.$alert('请先下架再进行结束操作!', {
          confirmButtonText: '确定',
          type: 'warning'
        });
      } else {
        this.$confirm('结束当前销售后不可恢复，请慎重操作，是否确定结束', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            set_sell_status({ id: Id, status: 2 }).then(res => {
              if (res.code == 1) {
                this.$message.success(res.message);
                this.list.splice(index, 1);
              }
            });
          })
          .catch(() => {});
      }
    },
    fetchData() {
      this.list = [];
      this.currentPage = 1;
      this.listLoading = true;
      this.formInline.status = this.status;
      if (this.formInline.sell_type == 1) {
        this.isPro = false;
      } else {
        this.isPro = true;
      }
      getPage(this.formInline)
        .then(response => {
          this.totalDataNumber = response.data.page * 20;
          getList(this.formInline).then(response => {
            this.getData(response.data);
            this.listLoading = false;
            this.formInline.coupons_id = '';
          });
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    getList() {
       this.saveFrom.coupons_id = '';
      if (this.search.sell_type == 1) {
        this.editPro = false;
      } else {
        this.editPro = true;
      }
      if( this.search.sell_type !=2 || (this.search.sell_type ==2 && this.search.type!=3 && this.search.type!=4)){
        this.isCashierDesk = true;  
      }else{
        this.isCashierDesk = false;
      }
      this.saveFrom.channel = 1;
      this.page = 1;
      get_coupons_list_page(this.search).then(response => {
        this.totalNumber = response.data.page * 20;
        get_coupons_list(this.search).then(response => {
          this.tableData = response.data;
          if (this.search.coupons_id) {
            let obj = this.tableData.find(item => {
              this.obj_type = item.type;
              return item.id == this.search.coupons_id;
            });
            if (this.obj_type == 8) {
              this.saveFrom.channel = 2;
            } else {
              this.saveFrom.channel = 1;
            }
            //this.search.coupons_id = '';
          }
        });
      });
    },
    //分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        this.getData(response.data);
        this.listLoading = false;
      });
    },
    handleCurrent(val) {
      get_coupons_list(this.search, val).then(response => {
        this.tableData = response.data;
      });
    },
    //下架
    changeClick(row) {
      if (row.status == 2 && row.is_sell == false) {
        this.$confirm('下架后，该券在该渠道下不可购买，也不可见。是否确定下架？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            set_sell_status({ id: row.id, status: 0 }).then(res => {
              if (res.code == 1) {
                this.$message.success(res.message);
                this.fetchData();
              }
            });
          })
          .catch(() => {
            row.is_sell = true;
          });
      } else {
        set_sell_status({ id: row.id, status: row.is_sell ? 1 : 0 }).then(res => {
          if (res.code == 1) {
            this.$message.success(res.message);
            this.fetchData();
          }
        });
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customContainer {
  overflow-y: auto;
}
.op_title {
  margin: 30px 0 20px;
  font-size: 16px;
  font-weight: bold;
  color: #282828;
  padding:0 0 10px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #dcdfe6;
}
.tab_title {
  width: 200px;
  font-size: 20px;
  font-weight: bold;
  margin: 5px 0 20px 70px;
}
.info {
  // margin-top: 20px;
  .content {
    background: #fff;
    margin-bottom: 20px;
    padding: 15px 20px;
    border: 1px solid #dfdfdf;
    overflow: hidden;
    .title {
      font-size: 15px;
      margin: 10px 0;
      line-height: 30px;
      font-weight: bold;
      color: rgba(40, 40, 40, 1);
      border-bottom: 1px solid rgba(220, 223, 230, 1);
    }
    .table /deep/ .el-radio__label {
      padding-left: 0;
    }
    .span {
      color: #999;
      line-height: 40px;
      margin-left: 20px;
      font-size: 13px;
    }
    i {
      color: #999;
      margin-left: 5px;
      margin-right: 20px;
      font-size: 13px;
      font-style: normal;
    }
  }
}
</style>